<?php

/**
 * Created by PhpStorm.
 * Script Name: Bottask.php
 * Create: 2020/5/24 上午10:25
 * Description: 定时任务
 * Author: fudaoji<fdj@kuryun.cn>
 */
namespace app\admin\controller;

use app\common\model\tpzs\Config;
use app\common\model\tpzs\Task;
use app\constants\Bot;
use ky\Jtt;

class Tpzstask extends Botbase
{
    /**
     * @var \app\common\model\tpzs\Task
     */
    protected $model;
    /**
     * @var array
     */
    private $tabList;
    private $configM;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Task();
        $this->configM = new Config();
        $this->tabList = [
            'todo' => [
                'title' => '待发送',
                'href' => url('index', ['name' => 'todo'])
            ],
            'done' => [
                'title' => '已发送',
                'href' => url('index', ['name' => 'done'])
            ],
        ];
    }

    public function index()
    {
        $name = input('name', 'todo');
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['bot_id' => $this->bot['id']];
            !empty($post_data['search_key']) && $where['content'] = ['like', '%' . $post_data['search_key'] . '%'];
            //isset($post_data['complete']) && $post_data['complete'] >= 0 && $where['complete_time'] = $post_data['complete'] == 0 ? 0 : ['>', 0];
            if($name == 'todo'){
                $where['complete_time'] = 0;
                $order = ['plan_time' => 'asc'];
            }else{
                $where['complete_time'] = ['>', 0];
                $order = ['complete_time' => 'desc'];
            }

            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList(
                    [$post_data['page'], $post_data['limit']], $where,
                    $order, true, true
                );
                foreach ($list as $k => $v){
                    $ids = explode(',', $v['members']);
                    if($member = model('admin/botMember')->getOneByMap([
                        'wxid' => $ids[0]
                    ])){
                        $v['members'] = $member['nickname'];
                        if(count($ids) > 1){
                            $v['members'] .= "等".count($ids)."个对象";
                        }
                    }else{
                        $v['members'] = "--";
                    }
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }

            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            //['type' => 'select', 'name' => 'complete', 'title' => '发送状态', 'options' => [-1 => '全部', 0 => '未发送', 1 => '已发送']],
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '内容']
        ])
            ->setTabNav($this->tabList, $name)
            ->setDataUrl(url('index', ['name' => $name]))
            //->addTopButton('addnew', ['title' => '快速添加', 'href' => url('quickAdd')])
            ->addTopButton('addnew', ['title' => '添加任务'])
            ->addTableColumn(['title' => '发送顺序', 'field' => 'id', 'type' => 'index'])
            ->addTableColumn(['title' => '类型', 'field' => 'type', 'type' => 'enum', 'options' => Task::types(),'minWidth' => 30])
            ->addTableColumn(['title' => '计划发送时间', 'field' => 'plan_time', 'minWidth' => 180, 'type' => 'datetime'])
            ->addTableColumn(['title' => '发送图片', 'field' => 'img', 'minWidth' => 100, 'type' => 'picture'])
            ->addTableColumn(['title' => '发送文本', 'field' => 'content', 'minWidth' => 200])
            ->addTableColumn(['title' => '发送对象', 'field' => 'members', 'minWidth' => 200])
            ->addTableColumn(['title' => '备注', 'field' => 'title', 'minWidth' => 60]);
            //->addTableColumn(['title' => '发送对象', 'field' => 'members', 'minWidth' => 200, 'type' => 'enum', 'options' => $groups = model('admin/botMember')->getField('wxid,nickname',['uin' => $this->bot['uin']])]);
        if($name == 'done'){
            $builder->addTableColumn(['title' => '完成时间', 'field' => 'complete_time', 'minWidth' => 180, 'type' => 'datetime']);
        }else{
            $builder->addTableColumn(['title' => '是否开启', 'field' => 'status', 'minWidth' => 70, 'type' => 'enum', 'options' => [0 => '停止', 1 => '开启']])
                ->addTableColumn(['title' => '操作', 'minWidth' => 120, 'type' => 'toolbar'])
                ->addRightButton('edit')
                /*->addRightButton('self', ['title' => '置顶', 'href' => url('topPost', ['id' => '__data_id__']), 'lay-event' => 'ajax'])
                ->addRightButton('delete', ['href' => url('delPost', ['id' => '__data_id__'])])*/;
        }

        return $builder->show();
    }

    /**
     * 删除
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delPost(){
        $id = input('id', 0, 'intval');
        if(! $data = $this->model->getOne($id)){
            $this->error('数据不存在');
        }
        $this->model->delOne($id);
        $list = $this->model->getAll([
            'where' => ['bot_id' => $this->bot['id'], 'status' => 1, 'complete_time' => 0, 'plan_time' => ['>', $data['plan_time']]],
            'field' => ['id','plan_time'],
            'order' => ['plan_time' => 'asc'],
            'refresh' => true
        ]);
        if(count($list) && $list[0]['id'] != $id){
            $step_tasktime = $this->configM->getStepTaskTime($this->adminInfo['id']);
            foreach ($list as $k => $v){
                $this->model->updateOne(['id' => $v['id'], 'plan_time' => $data['plan_time'] + $step_tasktime * $k]);
            }
        }
        $this->success('操作成功');
    }

    /**
     * 置顶
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function topPost(){
        $id = input('id', 0, 'intval');
        if(! $data = $this->model->getOne($id)){
            $this->error('数据不存在');
        }
        $list = $this->model->getAll([
            'where' => ['bot_id' => $this->bot['id'], 'status' => 1, 'complete_time' => 0],
            'field' => ['id','plan_time'],
            'order' => ['plan_time' => 'asc'],
            'refresh' => true
        ]);
        if($list[0]['id'] != $id){
            $data = $this->model->updateOne(['id' => $id, 'plan_time' => $list[0]['plan_time']]);
            $step_tasktime = $this->configM->getStepTaskTime($this->adminInfo['id']);
            $before = $data;
            foreach ($list as $k => $v){
                if($v['id'] == $id)  continue;
                $before = $this->model->updateOne(['id' => $v['id'], 'plan_time' => $before['plan_time'] + $step_tasktime]);
            }
        }
        $this->success('操作成功');
    }

    /**
     * 新增任务
     * @return mixed
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $data = [
            'admin_id' => $this->adminInfo['id'],
            'bot_id' => $this->bot['id'],
            'type' => Task::TYPE_BASIC
        ];
        $last_one = $this->model->getOneByOrder([
            'where' => ['admin_id' => $this->adminInfo['id'], 'bot_id' => $this->bot['id']],
            'field' => 'members',
            'order' => ['id' => 'desc']
        ]);
        if($last_one){
            $data['members'] = explode(',', $last_one['members']);
        }else if($gid = $this->configM->getConf(['admin_id' => $this->adminInfo['id'], 'bot_id' => $this->bot['id']], 'central_group')){
            $group = model('admin/botMember')->getOne($gid);
            $data['members'] = [$group['wxid']];
        }

        $groups = model('admin/botMember')->getField('wxid,nickname',['uin' => $this->bot['uin']]);
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('admin_id', 'hidden', 'adminid', 'adminid', [], 'required')
            ->addFormItem('bot_id', 'hidden', 'bot', 'bot', [], 'required')
            ->addFormItem('type', 'radio', '类型', '类型', Task::types(), 'required')
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则根据设置的发单间隔时间确定', [], '')
            ->addFormItem('members', 'chosen_multi', '发送对象', '发送对象', $groups, 'required')
            ->addFormItem('img', 'picture_url', '发送图片', '1M以内')
            ->addFormItem('content', 'textarea', '发送内容', '文本内容', [], 'style=min-height:150px;')
            ->addFormItem('title', 'text', '备注', '')
            ->setFormData($data);
        return $builder->show();
    }

    /**
     * 快速新增
     * @return mixed
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function quickAdd(){
        $tab = input('tab', 'check');
        $jtt = new Jtt(['appid' => config('system.site.jtt_appid'), 'appkey' => config('system.site.jtt_appkey')]);

        $builder = new FormBuilder();
        if($tab == 'check'){
            if(request()->isPost()){
                $url = input('goods_url');
                $res = $jtt->jdGoodsQuery([
                    'v' => 'v3',
                    'keyword' => $url
                ]);
                if(!$res && empty($res['totalCount'])){
                    $this->error('未找到商品');
                }
                $goods = $res['goods'][0];
                cookie('goodsInfo', ['skuId' => $goods['skuId'], 'goodsUrl' => $goods['goods_link']]);
                $this->success('已获取商品信息', url('quickAdd', ['tab' => 'submit']));
            }
            $builder->setPostUrl(url('quickAdd'))
                ->addFormItem('goods_url', 'text', '商品链接', '商品链接', [], 'required');
        }else{
            $cookie = cookie('goodsInfo');
            $goods = [
                'goods_img' => '',
                'link_content' => '',
            ];
            $res = $jtt->getGoodsList([
                'keyword' => $cookie['skuId']
            ]);
            if(!empty($res['data'])){
                $goods = $res['data'][0];
            }
            $db_goods = model('goods')->getOneByMap(['sku_id' => $cookie['skuId']]);
            if(!empty($db_goods['link_content'])){
                $goods['link_content'] = $db_goods['link_content'];
            }
            if(!empty($goods['link_content'])){
                $goods['link_content'] = str_replace(
                    ['[商品标题]', '[商品原价]', '[优惠价]', '[券面额]', '[商品原始链接]', '[优惠券链接]', '[商品推广链接]'],
                    [$goods['goods_name'], $goods['goods_price'], $goods['final_price'],
                        empty($goods['discount_price']) ? 0 : $goods['discount_price'],
                        $goods['goods_link'],
                        empty($goods['discount_link']) ? '' : $goods['discount_link'],
                        $goods['goods_link'],
                    ],
                    $goods['link_content']
                );
            }

            $data = [
                'admin_id' => $this->adminInfo['id'],
                'bot_id' => $this->bot['id'],
                'sku_id' => $cookie['skuId'],
                'img' => $goods['goods_img'],
                'content' => $goods['link_content']
            ];
            if($gid = model('botConfig')->getConf(['admin_id' => $this->adminInfo['id']], 'central_group')){
                $group = model('admin/botMember')->getOne($gid);
                $data['members'] = [$group['wxid']];
            }
            $groups = model('admin/botMember')->getField('wxid,nickname',['uin' => $this->bot['uin']]);
            $builder->setPostUrl(url('savePost'))
                ->addFormItem('admin_id', 'hidden', 'adminid', 'adminid', [], 'required')
                ->addFormItem('bot_id', 'hidden', 'bot', 'bot', [], 'required')
                ->addFormItem('plan_time', 'datetime', '发送时间', '不填则根据设置的发单间隔时间确定', [], '')
                ->addFormItem('members', 'chosen_multi', '发送对象', '发送对象', $groups, 'required')
                ->addFormItem('sku_id', 'text', '商品skuID', '商品skuID')
                ->addFormItem('img', 'picture_url', '发送图片', '1M以内')
                ->addFormItem('content', 'textarea', '发送内容', '文本内容')
                ->setFormData($data);
        }

        return $builder->show();
    }

    /**
     * 新增任务
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(){
        $id = input('id', 0, 'intval');
        if(!$data = $this->model->getOne($id)){
            $this->error('数据不存在');
        }
        $data['members'] = explode(',', $data['members']);
        $groups = model('admin/botMember')->getField('wxid,nickname',['uin' => $this->bot['uin']]);
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('type', 'radio', '类型', '类型', Task::types(), 'required')
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则根据设置的发单间隔时间确定', [], 'required')
            ->addFormItem('members', 'chosen_multi', '发送对象', '发送对象', $groups, 'required')
            //->addFormItem('sku_id', 'text', '商品skuID', '商品skuID')
            ->addFormItem('img', 'picture_url', '发送图片', '1M以内')
            ->addFormItem('content', 'textarea', '发送内容', '文本', [], 'style=min-height:150px;')
            ->addFormItem('title', 'text', '备注', '')
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost($jump = '', $data = []){
        $data = input('post.');
        $step_tasktime = $this->configM->getStepTaskTime($this->adminInfo['id']);
        $plan_time = time() + $step_tasktime;
        if(empty($data['plan_time'])){
            $last_task = $this->model->getOneByOrder([
                'where' => ['admin_id' => $this->adminInfo['id'], 'status' => 1, 'bot_id' => $this->bot['id'], 'plan_time' => ['>', time()]],
                'order' => ['plan_time' => 'desc'],
                'field' => 'plan_time'
            ]);
            if($last_task){
                $plan_time = $last_task['plan_time'] + $step_tasktime;
            }
        }else{
            $plan_time = strtotime($data['plan_time']);
        }
        $data['plan_time'] = $plan_time;
        if(empty($data['img']) && empty($data['content'])){
            $this->error('图片或文本内容必填一项');
        }
        $data['bot_id'] = $this->bot['id'];
        if (empty($data[$this->pk])) {
            $res = $this->model->addOne($data);
        } else {
            $old = $this->model->getOne($data['id']);
            $res = $this->model->updateOne($data);
            //$this->model->afterUpdatePlanTime($res, $old);
        }
        if ($res) {
            $this->success('数据保存成功', '/undefined');
        } else {
            $this->error('数据保存出错');
        }
    }
}